package org.budo.warehouse.service.impl;

import java.util.Arrays;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.budo.graph.annotation.SpringGraph;
import org.budo.support.javax.sql.util.JdbcUtil;
import org.budo.warehouse.service.api.IDataNodeService;
import org.budo.warehouse.service.api.JdbcExecuteService;
import org.budo.warehouse.service.api.ServiceDynamicBeanProvider;
import org.budo.warehouse.service.entity.DataNode;
import org.budo.warehouse.service.entity.Pipeline;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
@Service("jdbcExecuteServiceImpl")
public class JdbcExecuteServiceImpl implements JdbcExecuteService {
    @Resource
    private ServiceDynamicBeanProvider serviceDynamicBeanProvider;

    @Resource
    private IDataNodeService dataNodeService;

    @SpringGraph
    @Override
    public Integer executeUpdate(Pipeline pipeline, String sql, Object[] parameters) {
        Integer targetDataNodeId = pipeline.getTargetDataNodeId();
        String targetSchema=pipeline.getTargetSchema();
 
        DataNode targetDataNode = dataNodeService.findByIdCached(targetDataNodeId);
        DataSource dataSource = serviceDynamicBeanProvider.dataSource(targetDataNode, targetSchema);

        if (null == dataSource) {
            log.error("#37 dataSource=" + dataSource + ", targetDataNode=" + targetDataNode);
            return 0;
        }

        Integer updateCount = JdbcUtil.executeUpdate(dataSource, sql, parameters);

        if (null == updateCount || updateCount < 1) {
            log.warn("#56 sql=" + sql + ", parameters=" + Arrays.toString(parameters) + ", updateCount=" + updateCount);
        }

        return updateCount;
    }
}